package com.leoman.service.impl;

import com.leoman.controller.common.CommonController;
import com.leoman.core.Constant;
import com.leoman.dao.CompanyUserDao;
import com.leoman.dao.CompanyUserGainDao;
import com.leoman.entity.CompanyUser;
import com.leoman.entity.CompanyUserGain;
import com.leoman.entity.vo.AppUserGainPlusVo;
import com.leoman.exception.ParamErrorException;
import com.leoman.exception.UserNotFindException;
import com.leoman.exception.UserSealStatusException;
import com.leoman.service.CompanyUserGainService;
import com.leoman.utils.DateUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * CompanyUserGainServiceImpl
 * Created by 涂奕恒 on 2016/11/2 0002 上午 11:02.
 */
@Service
public class CompanyUserGainServiceImpl implements CompanyUserGainService {

    @Autowired
    private CompanyUserGainDao companyUserGainDao;

    @Autowired
    private CompanyUserDao companyUserDao;

    @Override
    public List<CompanyUserGain> findAll() {
        return companyUserGainDao.findAll();
    }

    @Override
    public Page<CompanyUserGain> find(int pageNum, int pageSize) {
        return companyUserGainDao.findAll(new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "id"));
    }

    @Override
    public Page<CompanyUserGain> find(int pageNum) {
        return find(pageNum, Constant.PAGE_DEF_SIZE);
    }

    @Override
    public CompanyUserGain getById(int id) {
        return companyUserGainDao.findOne(id);
    }

    @Override
    public void deleteById(int id) {
        companyUserGainDao.delete(id);
    }

    @Override
    public CompanyUserGain create(CompanyUserGain companyUserGain) {
        return companyUserGainDao.save(companyUserGain);
    }

    @Override
    public CompanyUserGain update(CompanyUserGain companyUserGain) {
        return companyUserGainDao.save(companyUserGain);
    }

    @Override
    @Transactional
    public void deleteAll(int[] ids) {
        for (int id : ids) {
            deleteById(id);
        }
    }

    @Override
    public Page<CompanyUserGain> iPageByCompanyUserId(Integer companyUserId, Integer pageNum, Integer pageSize) throws ParamErrorException, UserNotFindException, UserSealStatusException {
        AppUserServiceImpl.getCompanyUserInfo(companyUserId, companyUserDao);
        Integer[] info = CommonController.getPageParams(pageNum, pageSize);
        Page<CompanyUserGain> page = companyUserGainDao.iPageByUserId(companyUserId, new PageRequest(info[0] - 1, info[1]));

        for (CompanyUserGain companyUserGain : page.getContent()) {
            companyUserGain.setMonth(companyUserGain.getRecordDate());
            companyUserGain.setGainList(changeList(companyUserGainDao.findListByRecordDate(companyUserId, companyUserGain.getRecordDate())));
        }

        return page;
    }

    private List<AppUserGainPlusVo> changeList(List<CompanyUserGain> appUserGainList) {
        List<AppUserGainPlusVo> list = new ArrayList<>();
        AppUserGainPlusVo appUserGainPlusVo;

        for (CompanyUserGain appUserGain : appUserGainList) {
            System.out.println();
            appUserGainPlusVo = new AppUserGainPlusVo();
            appUserGainPlusVo.setGainId(appUserGain.getId());
            appUserGainPlusVo.setGainContent(appUserGain.getContent());
            appUserGainPlusVo.setGainMoney(appUserGain.getMoney());
            appUserGainPlusVo.setGainCreateTime(appUserGain.getCreateTime());

            list.add(appUserGainPlusVo);
        }

        return list;
    }

    @Override
    public Page<CompanyUserGain> pageByParams(final Integer companyUserGainId, final String mobile, final Integer type, Integer pageNum, Integer pageSize) {
        return companyUserGainDao.findAll(new Specification<CompanyUserGain>() {
            @SuppressWarnings("ToArrayCallWithZeroLengthArrayArgument")
            @Override
            public Predicate toPredicate(Root<CompanyUserGain> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Predicate result = null;
                List<Predicate> predicateList = new ArrayList<>();
                if (StringUtils.isNotBlank(mobile)) {
                    Predicate pre = cb.like(root.get("companyUser").get("mobile").as(String.class), "%" + mobile + "%");
                    predicateList.add(pre);
                }
                if (null != companyUserGainId) {
                    Predicate pre = cb.equal(root.get("id").as(Integer.class), companyUserGainId);
                    predicateList.add(pre);
                }
                if (null != type) {
                    Predicate pre = cb.equal(root.get("type").as(Integer.class), type);
                    predicateList.add(pre);
                }

                Predicate pre1 = cb.gt(root.get("money").as(Integer.class), 0);
                predicateList.add(pre1);

                if (predicateList.size() > 0) {
                    result = cb.and(predicateList.toArray(new Predicate[]{}));
                }

                if (result != null) {
                    query.where(result);
                }
                return query.getGroupRestriction();
            }

        }, new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "id"));
    }

    @Override
    public Page<CompanyUserGain> pageByParams(final Integer companyUserId, final Integer status, final String startTime, final String endTime, Integer pageNum, Integer pageSize) {
        return companyUserGainDao.findAll(new Specification<CompanyUserGain>() {
            @SuppressWarnings("ToArrayCallWithZeroLengthArrayArgument")
            @Override
            public Predicate toPredicate(Root<CompanyUserGain> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Predicate result = null;
                List<Predicate> predicateList = new ArrayList<>();
                if (null != companyUserId) {
                    Predicate pre = cb.equal(root.get("companyUser").get("id").as(Integer.class), companyUserId);
                    predicateList.add(pre);
                }
                if (null != status) {
                    // 1=收入，2=支出
                    if (status == 1) {
                        predicateList.add(cb.gt(root.get("money").as(Integer.class), 0));
                    } else {
                        predicateList.add(cb.lt(root.get("money").as(Integer.class), 0));
                    }
                }

                predicateList.add(cb.notEqual(root.get("money").as(Integer.class), 0));

                predicateList.add(cb.isNotNull(root.get("updateTime").as(Long.class)));

                if (StringUtils.isNotBlank(startTime)) {
                    try {
                        Long startDate = DateUtils.stringToDateWithFormat(startTime, "yyyy-MM-dd hh:mm:ss").getTime();
                        predicateList.add(cb.gt(root.get("createTime").as(Long.class), startDate));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }

                if (StringUtils.isNotBlank(endTime)) {
                    try {
                        Long endDate = DateUtils.stringToDateWithFormat(endTime, "yyyy-MM-dd hh:mm:ss").getTime();
                        predicateList.add(cb.lt(root.get("createTime").as(Long.class), endDate));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }

                if (predicateList.size() > 0) {
                    result = cb.and(predicateList.toArray(new Predicate[]{}));
                }

                if (result != null) {
                    query.where(result);
                }
                return query.getGroupRestriction();
            }

        }, new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "id"));
    }

    @Override
    public Boolean changeStatus(Integer companyUserGainId) {
        try {
            CompanyUserGain companyUserGain = companyUserGainDao.findOne(companyUserGainId);
            if (null == companyUserGain) {
                return false;
            }

            if (null != companyUserGain.getUpdateTime()) {
                return true;
            }

            companyUserGain.setUpdateTime(System.currentTimeMillis());
            companyUserGainDao.save(companyUserGain);

            // 扣除手续费
            CompanyUserGain gainPlus = new CompanyUserGain();
            gainPlus.setCompanyUser(companyUserGain.getCompanyUser());
            gainPlus.setType(companyUserGain.getType());
            gainPlus.setContent("手续费");
            Double money = companyUserGain.getMoney() * 15 / 100 * -1;
            gainPlus.setMoney(money);
            gainPlus.setRecordDate(DateUtils.dateToStringWithFormat(new Date(), "yyyy-MM"));
            gainPlus.setUpdateTime(System.currentTimeMillis());

            companyUserGainDao.save(gainPlus);

            CompanyUser companyUser = companyUserGain.getCompanyUser();
            companyUser.setMoney(companyUser.getMoney() + companyUserGain.getMoney() + money);
            companyUserDao.save(companyUser);

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public Integer addMoney(Integer companyUserId, Double money) throws ParamErrorException {
        if (null == companyUserId || null == money) {
            throw new ParamErrorException();
        }

        CompanyUser companyUser = companyUserDao.findOne(companyUserId);

        CompanyUserGain companyUserGain = new CompanyUserGain();
        companyUserGain.setCompanyUser(companyUser);
        companyUserGain.setContent("充值");
        companyUserGain.setMoney(money);

        return companyUserGainDao.save(companyUserGain).getId();
    }
}